package com.springbootblog.interceptor;

//import com.springbootblog.config.JwtConfig;
import com.springbootblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter
{
//    @Resource
//    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws SignatureException, IOException
    {
        /** 地址过滤 */
        String uri = request.getRequestURI() ;
        System.out.println("uri="+uri);
        // 登录接口 放行
        if (uri.contains("/java/login/accountLogin"))
        {
            return true ;
        }
        // Token 验证 从请求头获取token
        String token = request.getHeader(JwtUtils.token_name);
        if(StringUtils.isEmpty(token))
        {
            token = request.getParameter(JwtUtils.token_name);
        }
        if(StringUtils.isEmpty(token))
        {
            // throw new SignatureException(JwtUtils.token_name+ "不能为空");
            return true;
        }
        System.out.println(token);
        if(token.equals("undefined"))
        {
            return true;
        }
        Claims claims = null;
        try
        {
            claims = JwtUtils.parseJWT(token);
            if(claims == null || JwtUtils.isTokenExpired(claims.getExpiration()))
            {
                /*// 调用方法设置response
                this.updateResponse(response, request);
                // 直接写入响应体
                String jsonResponse = "{\"code\": \"-150\",\"msg\": \"Token失效，请重新登陆！\"}";
                //System.out.println("filter-map:"+jsonResponse);
                response.getWriter().write(jsonResponse);
                return false;//*/
            }
        }
        catch (Exception e)
        {
            // throw new SignatureException("失效，请重新登录。");

            /*// 调用方法设置response
            this.updateResponse(response, request);
            // 直接写入响应体
            String jsonResponse = "{\"code\": \"-150\",\"msg\": \"Token失效，请重新登陆！\"}";
            //System.out.println("filter-map:"+jsonResponse);
            response.getWriter().write(jsonResponse);
            return false;//*/
        }
        //该token可用，放行
        return true;
    }

    /**
     * 设置response头部返回信息
     * @param response
     * @param request
     * @return
     */
    public HttpServletResponse updateResponse(HttpServletResponse response, HttpServletRequest request)
    {
        // 设置头部返回信息
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,token");//这里“Access-Token”是我要传到后台的内容key
        response.addHeader("Access-Control-Expose-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Cache-Control", "no-cache");
        // 设置前端状态码和内容类型 设置响应状态码为 200。
        response.setStatus(HttpServletResponse.SC_OK);
        // 设置响应内容类型
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        return response;
    }

}
